﻿using AntMovement.Core;
using AntMovement.Custom.Domain.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AntMovement.Custom.Domain
{
    public class LogPersistence : ILogPersistence
    {
        private ConcurrentQueue<ErrorDataModel> _queue = new ConcurrentQueue<ErrorDataModel>();
        public LogPersistence()
        {
            
        }

        public void Write(string type, string message)
        {
            _queue.Enqueue(new ErrorDataModel() { Type = type, Messgae = message });
            Execute();
        }

        private volatile int _lock = 0;
        private void Execute()
        {
            if (Interlocked.Exchange(ref _lock, 1) == 0)
            {
                Task.Run(() => {
                    while (_queue.Count > 0)
                    {
                        _queue.TryDequeue(out ErrorDataModel model);
                        if (model != null)
                        {
                            //还在考虑到底写日志还是写数据库
                            
                        }
                        Thread.Sleep(20);
                    }
                    Interlocked.Exchange(ref _lock, 0);
                });
            }
        }
    }
}
